package com.play.ballen.me.dialog

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.play.ballen.R
import com.play.ballen.interfaces.BottomSheetEntityContract
import com.play.ballen.me.adapter.BottomSheetDialogAdapter

class BottomSheetDialogUtils<T : BottomSheetEntityContract>(private val mContext: Context) {

    private lateinit var dialog: BottomSheetDialog

    private val adapter: BottomSheetDialogAdapter<T> by lazy {
        BottomSheetDialogAdapter(arrayListOf())
    }

    var itemCallback: ((T) -> Unit)? = null

    fun show(items: List<T>?) {
        if (items.isNullOrEmpty()) {
            return
        }
        if (!this::dialog.isInitialized) {
            val view =
                LayoutInflater.from(mContext).inflate(R.layout.dialog_team_center_percent, null)
            val rv = view.findViewById<RecyclerView>(R.id.rv)
            val tvCancel = view.findViewById<TextView>(R.id.tvCancel)
            val tvOK = view.findViewById<TextView>(R.id.tvOK)

            rv.layoutManager = LinearLayoutManager(mContext)
            adapter.select = items[0]   //默认第一个选中
            rv.adapter = adapter
            adapter.setOnItemClickListener { a, view, position ->
                adapter.select = adapter.data[position]
                adapter.notifyDataSetChanged()
            }

            dialog = BottomSheetDialog(mContext)
            dialog.setContentView(view)
            dialog.delegate.findViewById<View>(R.id.design_bottom_sheet)!!.setBackgroundColor(
                mContext.resources.getColor(android.R.color.transparent)
            )
            val onClickListener = View.OnClickListener { v: View ->
                dialog.dismiss()
                when (v.id) {
                    R.id.tvCancel -> dialog.dismiss()
                    R.id.tvOK -> {
                        val select = adapter.select ?: return@OnClickListener
                        itemCallback?.invoke(select)
                        dialog.dismiss()
                    }
                }
            }
            tvCancel.setOnClickListener(onClickListener)
            tvOK.setOnClickListener(onClickListener)
        }
        adapter.setList(items)

        if (!dialog.isShowing) {
            dialog.show()
        }
    }

}